<template>
<div class="bigbox">
  <div class="box">
    <div class="addresss" @click="toaddr">✈{{address}}</div>
    <!-- 文字较短时，通过设置 scrollable 属性开启滚动播放 -->
    <van-notice-bar scrollable text="千大牌任你挑-全场5折-抢百亿优惠券享折后再折-双十一来了-好货提前看-快来抢购吧！" />
    <!-- 优惠券单元格 -->
    <van-coupon-cell
      :coupons="coupons"
      :chosen-coupon="chosenCoupon"
      @click="showList = true"
    />
    <!-- 优惠券列表 -->
    <van-popup
      v-model="showList"
      round
      position="bottom"
      style="height: 90%; padding-top: 4px;"
    >
      <van-coupon-list
        :coupons="coupons"
        :chosen-coupon="chosenCoupon"
        :disabled-coupons="disabledCoupons"
        @change="onChange"
        @exchange="onExchange"
      />
    </van-popup>
    <van-empty v-if="carts.length === 0" class="custom-image" 
    image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
    description="购物车空空如也，快去挑选商品吧！" />
    <div class="noempty" v-else>
      <div class="carts">
          <van-card
            v-for="cart in carts"
            :key="cart.id"
            :num="cart.number"
            :desc="cart.specs"
          >
            <template #thumb>
              <van-checkbox @change="checkedOne" 
              v-model="cart.checked"></van-checkbox>
              <img :src="cart.banner" />
            </template>
            <template #title>
              <b>{{ cart.name }}</b>
            </template>
            <template #price>
              <span style="color: red">￥{{ cart.price }}</span>
            </template>
            <template #num>
              <van-button @click="reduceNum(cart.id)" round 
              size="mini" plain type="info">-</van-button>
              <span class="pronum">{{ cart.number }}</span>
              <van-button @click="addNum(cart.id)" round 
              size="mini" type="danger">+</van-button>
            </template>
            <template #bottom>
              <br />
              小计： <span>￥{{ cart.subtotal }}</span>
            </template>
            <template #price-top> <span @click="del(cart.id)" class="remove">×</span> </template>
          </van-card>
      </div>
    </div>
    <div class="jiesuan">
      <div class="settle">
        <van-checkbox @click="checkedAll()" v-model="checkAll" checked-color="blue"
          ><span class="quanxuan">全选</span></van-checkbox>
        <div class="text">

          <p>实付：￥{{totalPrice}}</p>
          <p>已优惠：￥{{youhui}}</p>
        </div>
        <van-button round plain>去结算{{totalNum}}</van-button>
      </div>
    </div>
  </div>
</div>
</template>

<script>
import { getCookie } from "@/utils/cookie";
import { getCartsPro, editCart, delCart, getDefaultAddr} from "@/request";
import Vue from "vue";
import { Card } from "vant";
import { Checkbox, CheckboxGroup } from "vant";
import { Button } from "vant";
import { operate } from "@/utils/math";
import { Dialog } from 'vant';
import { Toast } from 'vant';
import { SwipeCell } from 'vant';
import { Empty } from 'vant';
import { CouponCell, CouponList } from 'vant';
import { NoticeBar } from 'vant';
import { Popup } from 'vant';

Vue.use(Toast);
Vue.use(Popup);
Vue.use(NoticeBar);
Vue.use(CouponCell);
Vue.use(CouponList);
Vue.use(Empty);
Vue.use(SwipeCell);
Vue.use(Button);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Card);

const coupon = {
  available: 1,
  condition: '无使用门槛\n最多优惠20元',
  reason: '',
  value: 850,
  name: '双十一无门槛券',
  startAt: 1589104000,
  endAt: 1614592000,
  valueDesc: '8.5',
  unitDesc: '元',
};

const coupon1 = {
  available: 1,
  condition: '无使用门槛\n最多优惠20元',
  reason: '',
  value: 1050,
  name: '双十一无门槛券',
  startAt: 1589104000,
  endAt: 1614592000,
  valueDesc: '10.5',
  unitDesc: '元',
};
export default {
  data() {
    return {
      carts: [],
      checkAll: false,
      chosenCoupon: -1,
      coupons: [coupon],
      disabledCoupons: [coupon1],
      showList: false,
      address:''
    };
  },
  created() {
    var username = getCookie("username");
    if (!username) {
      localStorage.setItem("url", "/cart");
      this.$router.push("/my/login");
    }
    getCartsPro().then((data) => {
      this.carts = data.map((item) => {
        // 每个商品的选中状态
        item.checked = false;
        // 小计
        item.subtotal = operate(item.price, item.number, "*");
        return item;
      });
    })
    getDefaultAddr().then(data => {
        console.log(data);
        if(data.code === 1){
          this.address = data.data.name + ',' + data.data.tel + ','
          + data.data.address
        }else{
          this.address = '请先添加地址'
        }
    })
  },
  methods: {
    //优惠券切换回调
    onChange(index) {
      this.showList = false;
      this.chosenCoupon = index;
    },
    //兑换优惠券回调
    onExchange(code) {
      this.coupons.push(coupon);
    },
    addNum(id){
    // 让当前商品的数量自增 - 先获取当前商品的数量
    // 根据当前商品的id，从所有商品中获取到当前这个商品
      var cart = this.carts.find(item => item.id === id)
      // 让商品的数量自增
      cart.number++
      // 让商品中的小计跟随数量变化后重新计算
      cart.subtotal = operate(cart.price, cart.number,'*')
      // 这里的数据发生了变化， 就是carts数据发生了变化，页面也就会自动发生变化
      editCart(cart).then(data =>{
        console.log(data);
      })
    },
    reduceNum(id){
      var cart = this.carts.find(item => item.id === id)
      
      if(cart.number <= 1){//商品数量为1时无法继续减
        return
      }else{//否则商品数量减1
        cart.number--
        //重新获取商品数据
        cart.subtotal = operate(cart.price,cart.number,'*')
        editCart(cart).then(data => {
          console.log(data);
        })
      }
      cart.subtotal = operate(cart.price, cart.number,'*')
      editCart(cart).then(data =>{
        console.log(data);
      })
    },
    checkedAll(){
      // 判断数据中的全选数据是真还是假，设置其他的商品单选是否选中
      this.carts.forEach(item => {
        item.checked = this.checkAll
      })
    },
    checkedOne(){
      // 判断是否所有的商品都选中了
      // 判断carts中每一个对象的checked是否都是true
      // var bool = this.carts.every(item => item.checked)
      // 根据上面的布尔值设置全选
      // this.checkAll = bool

      // 简写：
      this.checkAll = this.carts.every(item => item.checked)
    },
    del(id) { 
      // 询问用户 
      Dialog.confirm({ 
        title: '购物车删除', 
        message: '你真的要删除掉这个商品吗？', 
      }) 
      .then(() => { 
        // 真的要删除 
        // on confirm 
        // console.log('确认'); 
        // 从carts中删除数据 
        // 数组.splice(开始下标, 删除个数) 
        // 从carts中找到当前要删除的商品数据的下标 
        var index = this.carts.findIndex(item => item.id === id) 
        // 根据下标进行删除 
        this.carts.splice(index, 1) 
        // 发送请求从daa.json中删除数据 
        delCart(id).then(data => {
          Toast.success(data.msg);
        })
      }) 
      .catch(() => { 
        // 不是要删除 
        // on cancel 
        // console.log('取消'); 
        // 取消删除操作 
        Toast.success('已取消！'); 
      }); 
    },
    toaddr(){
      //跳转到地址页面
      this.$router.push('/address')
    }
  },
   // 用来统计的，当一个数据会通过其他数据计算得到，并随着其他数据的变化而变化的时候，就使用computed
  computed:{
    //优惠券金额返回
    youhui(){
      var chosenCoupon = this.chosenCoupon
      var coupon = this.coupons.filter(coupon => coupon.valueDesc)
      var n = 0
      if (chosenCoupon != -1){
        coupon.forEach(coupon => {
        n = coupon.valueDesc
      })
      }else{
        n = 0
      }
      return n
    },
    // 这里的key，表示我们要在页面中使用的数据名称
    // 这里value，是一个函数，用于写计算的代码 - return 结果
    totalPrice(){
      //获取优惠券信息
      var chosenCoupon = this.chosenCoupon
      var coupon = this.coupons.filter(coupon => coupon.valueDesc)
      // 先找到所有被选中的商品
      var carts = this.carts.filter(item => item.checked)
      var n = 0
      var a = 0
     if (chosenCoupon != -1){
        coupon.forEach(coupon => {
        a = coupon.valueDesc
      })
      }else{
        a = 0
      }
      carts.forEach(item => {
        n = n + item.subtotal
        console.log(n)
        }
      )
      //总金额减去优惠券金额
      n = n - a
      console.log(n)
      return n
    },
    totalNum(){
      var carts = this.carts.filter(item => item.checked)
      var n = 0
      carts.forEach(item => n += item.number)
      return n
    }
  }
};
</script>

<style scoped>
.carts .van-card{
  background-color: rgb(255,0,0,0.1);
}
.carts img {
  width: 80px;
  height: 100px;
  margin-left: 40px;
}
.carts .van-checkbox {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
}
.van-card__thumb {
  width: 130px;
}
.van-card__num .van-button {
  width: 20px;
  height: 20px;
  font-size: 18px;
  vertical-align: top;
}
.pronum {
  margin: 0 10px;
  font-size: 16px;
}
.van-card__content > div:first-child{
  margin-right: 170px;
}
.van-card__num {
  margin-right: 100px;
}
.remove {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  right: 0;
  font-size: 20px;
  padding: 10px;
}
.jiesuan {
  position: fixed;
  bottom: 50px;
  left: 0;
  width: 100%;
  background-color: #f00;
}
.settle {
  display: flex;
  justify-content: space-between;
  padding: 10px 20px;
  align-items: center;
  color: #fff;
}
.settle .quanxuan{
  color: #fff;
}
.settle .text {
  flex: 1;
  padding-left: 20px;
}
.settle .text p {
  padding: 0;
  margin: 0;
}
.custom-image .van-empty__image {
    width: 90px;
    height: 90px;
}
.addresss{
  font-size: 18px;
  height: 40px;
  padding: 20px 20px 20px 20px;
  background-color: #FF0000;
  color: white;
  text-align: center;
  border-bottom:2px solid #ccc;
  font-weight: bold;
  font-family: '微软雅黑','Courier New', Courier, monospace;
}
</style>